App.Modules.Gmail = function(obj) {
	var data = obj.dataObj.data;
	var localData = new Object();
	var el = obj.elm_moduleContent;
	localData.isLogged = false;

	if (data.showCount == null)	{
		data.showCount = 1;
	}

	this.edit = function() {
		var editContent = obj.elm_editContent;

		var form = document.createElement("form");
		form.onsubmit = ajaxCall;

		// Default value of nbTitles ;-)
		if (data.nbTitles == null || data.nbTitles == 0)
			data.nbTitles = 6;

		function ajaxCall() {
			obj.dataObj.title = _("Gmail");
			obj.elm_title.innerHTML = _("Gmail") + " : <em>" + _("Loading...") + "</em>";

			var param = "url="+escape("https://"+encodeURIComponent(input1.value)+":"+encodeURIComponent(input2.value)+"@mail.google.com/mail/feed/atom");
			App.Request.sendPOST(NV_PATH+'proxy/securePassProxy.php', param, displayEmailsCheck, "Gmail");

			return false;
		}

		var content = '<table cellpadding="0" cellspacing="0" class="formTable">'+
					'<tr>'+
						'<td><label>' + _("Title:") + '</label></td>'+
						'<td><input type="text" class="inputClean" accesskey="t" maxlength="150" value="" style="width:75px"/><input type="button" value="'+_("Save")+'" class="buttonClean"/></td>'+
					'</tr>'+
					'<tr style="height:10px"><td colspan="2"><hr /></td></tr>'+
					'<tr>'+
						'<td><label>' + _("Login:") + '</label></td>'+
						'<td><input type="text" class="inputClean" accesskey="t" maxlength="150" value="" style="width:75px"/></td>'+
					'</tr>'+
					'<tr>'+
						'<td><label>' + _("Password:") + '</label></td>'+
						'<td><input type="password" class="inputClean" accesskey="t" maxlength="150" style="width:75px"/><input type="submit" value="'+_("Save")+'" class="buttonClean"/></td>'+
					'</tr>'+
					'<tr>'+
						'<td><label>' + _("Nb Mails:") + '</label></td>'+
						'<td><select style="width:45px">'+getOptionList()+'</select></td>'+
					'</tr>'+
					'<tr>'+
						'<td><label>' + _("Show number of unread e-mails in the title:") + '</label></td>'+
						'<td><input type="checkbox"></td>'+
					'</tr>'+
				'</table>';
		form.innerHTML = content;
		editContent.appendChild(form);

        var inputs = form.getElementsByTagName("input");
		var tbTitle = inputs[0];
		var bSaveTitle = inputs[1];
		var input1 = inputs[2];
		var input2 = inputs[3];
		var sNbItems = form.getElementsByTagName("select")[0];

		tbTitle.value = data.title || "";
		input1.value = data.login || "";

		bSaveTitle.onclick = function() {
			data.title = tbTitle.value.trim();
			obj.save();

			setModuleTitle();
		};

		sNbItems.onclick = function() {
			data.nbTitles = this.value;

			// We save the object and display items only if the
			// module is configured
			if (data.login != null && data.login != "") {
				obj.save();
				// Refresh the display
				if (localData.isLogged) displayEmails2();
			}
		};
		
		if (data.showCount == 1) {
			inputs[5].checked = "checked";
		}
		
		inputs[5].onclick = function() {
			if (data.showCount == 1) data.showCount = 0;
			else data.showCount = 1;
			obj.save();
			setModuleTitle();
		}

		function displayEmailsCheck(response) {
			if (response.status == 503) {
				alert("GMail is not in service. Sorry.");
				response.responseXML = null;
			}
			if (response.responseText != "") {
				data.login = input1.value;
				data.pass = input2.value;
				obj.save();
				obj.dataObj.history = "";
			}
			displayEmails(response);
		};

		function getOptionList() {
			var c='';

			for (var z=0; z<20; z++) {
				if ((z+1)==data.nbTitles) {
					c+='<option value="'+(z+1)+'" selected>'+(z+1);
				} else {
					c+='<option value="'+(z+1)+'">'+(z+1);
				}
			}
			return c;
		}
	};

	function displayItems(sum) {
		var listNode = el.firstChild.nextSibling;
		var dl = document.createElement("dl");
		dl.className = "nv-emailList";
		var dt, dd, a, strong, p;
		var nbTitlesToDisplay = (localData.feed.items.length>data.nbTitles) ? data.nbTitles : localData.feed.items.length;
		if (App.isOnSearch) {
			var leftItem = nbTitlesToDisplay;
			nbTitlesToDisplay = localData.feed.items.length;
			results = 0;
		}

		var domain = data.login.match(/@(.*)$/);
		domain = (domain && domain[1]!='gmail.com') ? domain[1] : false;
		
		for (var z=0; z<nbTitlesToDisplay; z++) {

			var title = localData.feed.items[z].title.unescapeHTML();
			var link = localData.feed.items[z].link.unescapeHTML().replace("http://", "https://");
			if (domain) link = link.replace('mail?', 'a/' + domain + '/mail?'); // change url if we use a personalised domain (google app)
			
			var name = (localData.feed.items[z].name || "").unescapeHTML();
			var summary = localData.feed.items[z].content.unescapeHTML();

			if (App.isOnSearch) {
				if (leftItem < 1) {
					results++;
					continue;
				}
				if (title.toLowerCase().indexOf(App.query.toLowerCase()) >= 0 || name.toLowerCase().indexOf(App.query.toLowerCase()) >= 0 || summary.toLowerCase().indexOf(App.query.toLowerCase()) >= 0) {
					leftItem--;
					results++;
				}
				else continue;
			}

			dt = document.createElement("dt");
/*			if (localData.feed.history.postStatus[z]==1) {
				dt.className = "read";
			} else {*/
				dt.className = "unread";
//			}
			a = document.createElement("a");
			a.href = link;
			a.target = "_blank";
			a.setAttribute("itemNum", z);
			strong = document.createElement("strong");
			strong.className = "sender";
			strong.appendChild(document.createTextNode(name));
			a.appendChild(strong);
			a.appendChild(document.createTextNode(" - " + title));
			if (App.isOnSearch) a.innerHTML = String.highlight(a.innerHTML,App.query);
			dt.appendChild(a);
			dl.appendChild(dt);

			dd = document.createElement("dd");
			if (sum) {
				p = document.createElement("p");
				p.appendChild(document.createTextNode(summary));
				if (App.isOnSearch) p.innerHTML = String.highlight(p.innerHTML,App.query);
				dd.appendChild(p);
			}
			dl.appendChild(dd);
		}
		listNode.innerHTML = "";
		listNode.appendChild(dl);
		var links = listNode.getElementsByTagName("a");

		function manageMiddleClick(e) {
			saveClickStatus(e.currentTarget);
		}

		function saveClickStatus(elem) {
		    if(!elem) return false;
			/*var num = elem.getAttribute("itemNum");
			if (localData.feed.history.postStatus[num]!=1) {
				localData.feed.history.postStatus[num] = 1;
				obj.dataObj.history = App.Rss.getHistoryString(localData.feed);
				//obj.saveHistory();
				//elem.firstChild.style.fontWeight = "normal";
				Element.removeClassName(elem.parentNode, 'unread');
				Element.addClassName(elem.parentNode, 'read');
				//setModuleTitle();
			}*/
			Element.removeClassName(elem.parentNode, 'unread');
			Element.addClassName(elem.parentNode, 'read');
		}

		var ln = links.length;
		for (var z=0; z<ln; z++) {
			links[z].onclick = function() {
				saveClickStatus(this);
			};
			//links[z].attachEvent('onmousedown', manageMiddleClick);
			Event.observe(links[z], 'mousedown', manageMiddleClick, false);
		}

	}

	function setModuleTitle() {
		if (localData.feed) {
			if (data.showCount == 1 && localData.feed) {
				var fullcount = localData.feed.fullcount;
			} else {
				var fullcount = 0;
			}
			if (!App.isOnSearch) {
				obj.dataObj.unRead = fullcount;
				obj.setUnread(fullcount);
			}
		}
		var title = "";
		if (data.title && data.title != "") {
			title = data.title;
		} else if (localData.feed && localData.feed.title) {
			var titleName = localData.feed.title;
			if (titleName) {
				titleName = titleName.replace("Gmail - Inbox for ", "");
				title = _("Inbox for {0}").format(titleName);
			}
		}

		obj.elm_title.innerHTML = "";
		var a = document.createElement("a");
		a.href = "https://mail.google.com/mail";
		a.target = "_blank";
		a.appendChild(document.createTextNode(_("Gmail")));
		obj.elm_title.appendChild(a);
		if (title != "") {
			obj.elm_title.appendChild(document.createTextNode(" : "));
			var em = document.createElement("em");
			em.appendChild(document.createTextNode(title));
			obj.elm_title.appendChild(em);
			if (!App.isOnSearch) {
				if (typeof fullcount != "undefined" && fullcount > 0) {
					obj.elm_title.appendChild(document.createTextNode(" "));
					var span = document.createElement("span");
					span.className = "unread";
					span.appendChild(document.createTextNode('(' + fullcount + ')'));
					obj.elm_title.appendChild(span);
				}
			} else {
				if (results > 0) fullcount = results;
				else fullcount = _("no results");

				obj.elm_title.appendChild(document.createTextNode(" "));
				var span = document.createElement("span");
				span.className = "result";
				span.appendChild(document.createTextNode('(' + fullcount + ')'));
				obj.elm_title.appendChild(span);
			}
		}

		function killEvent(e) {e.cancelBubble = true;}
		Event.observe(obj.elm_title.firstChild, 'mousedown', killEvent, false);
		
		if (obj.needMobileUpdate) {
			obj.needMobileUpdate();
		}
	}

	function displayEmails(response) {
		localData.feed = new Feed(response);
		displayEmails2();
		obj.onLoadModule();
	}

	function displayEmails2() {
		if (!localData || !localData.feed || localData.feed.error || !localData.feed.items) {
			setModuleTitle();
			el.innerHTML = '<table cellpadding="0" cellspacing="0" width="100%"><tr><td width="27"><img src="'+NV_PATH+'modules/mailWizard/img/gmail.png" width="27" height="20"/></td><td style="padding-left:5px">'+_("No info for this account, check your login and password and try again")+'</td></tr></table>';
			localData.isLogged = false;
			obj.refreshMode = false;
		} else {

			var fullcount = Number(localData.feed.fullcount);
			localData.isLogged = true;
			obj.refreshMode = true;

			var titleName = localData.feed.title;
			titleName = titleName.substring(7, titleName.length);

			if (localData.feed.items.length>0) {
				App.Rss.buildHistory(obj.dataObj.history, localData.feed);
				//data.nbTitles=6;
				//data.nbTitles = (localData.feed.items.length>data.nbTitles) ? data.nbTitles : localData.feed.items.length;
				var headerContent = '<table cellpadding="0" cellspacing="0" class="emailHeader" style="margin:2px 0 5px 6px;"><tr>'+
							'<td width="27"><img src="'+NV_PATH+'modules/mailWizard/img/gmail.png" width="27" height="20"/></td>'+
							'<td style="font-weight:bold;padding-left:5px">' + _("Total unread") + ':<span class="unread"> ' + fullcount + '</span></td>'+
							'<td class="emailCheckbox"><input type="checkbox" title="' + _("Show details") + '"/></td>'+
							'</tr></table><div></div>';
				el.innerHTML = headerContent;

				var isSum = (data.sum==0 || !data.sum) ? false : true;
				displayItems(isSum);
				var checkInput = el.firstChild.firstChild.firstChild.childNodes[2].firstChild;
				checkInput.checked = isSum;

				checkInput.onclick = function() {
					data.sum = ((this.checked) ? 1 : 0);
					obj.save();
					displayItems(this.checked);
				};
				setModuleTitle();

			} else {
				el.innerHTML = '<table cellpadding="0" cellspacing="0" width="100%"><tr><td width="27"><img src="'+NV_PATH+'modules/mailWizard/img/gmail.png" width="27" height="20"/></td><td style="padding-left:5px">'+_("No unread messages")+'</td></tr></table>';
				setModuleTitle();
			}
		}

	}

	function displayDefault() {
		el.innerHTML = '<table cellpadding="0" cellspacing="0" width="100%"><tr><td width="27"><img src="'+NV_PATH+'modules/mailWizard/img/gmail.png" width="27" height="20"/></td><td style="padding-left:5px">'+_("Account not configured, use the Edit link to set your login and password")+'</td></tr></table>';
		setModuleTitle();
		obj.onLoadModule();
	}

    // use secureproxy if moduleId is defined
    // else (previewed mode) use classic way to do, then save password securely if possible
    function requestSecureFeed(moduleId, login, password) {
        if (moduleId) {
            var param = "getPass=1&login=" + login + "&moduleId=" + moduleId;
            App.Request.sendPOST(NV_PATH + 'proxy/securePassProxy.php', param, displayEmails, "Gmail");
        } else {
			var param = "url="+escape("https://"+encodeURIComponent(login)+":"+encodeURIComponent(password)+"@mail.google.com/mail/feed/atom");
			App.Request.sendPOST(NV_PATH+'proxy/securePassProxy.php', param, displayEmailsCheck, "Gmail");
        }
    }
	function displayEmailsCheck(response) {
		if (response.status == 503) {
			alert("GMail is not in service. Sorry.");
			response.responseXML = null;
		}
		if (response.responseText != "") {
			obj.save();
			obj.dataObj.history = "";
		}
		displayEmails(response);
	};
        
	if (!data.login) {
		displayDefault();
	} else {
        requestSecureFeed(obj.dataObj.id, data.login, data.pass);
	}
    
	function updateFeed() {
		if (localData.isLogged) {
			obj.elm_title.innerHTML = '<em>'+_("Updating")+'...</em>';
            requestSecureFeed(obj.dataObj.id, data.login, data.pass);
		}
	};

	this.refresh = function() {
		updateFeed();
	};

	this.unload = function() {
		delete localData.feed;
		localData.feed = null;
		delete localData;
		localData = null;
	};

	var rndUpdateTime = Math.round(60*1000*Math.random()); // to make sure all the feeds doesn't update at the same time
	setInterval(updateFeed, 1000*60*30+rndUpdateTime); // update every 30 min

	var results;

	this.doSearch = function(query) {
		if (query != "") {
			results = 0;
			try { displayEmails2(); } catch(e) {};
			obj.dataObj.unRead = results;
			obj.setUnread(results);
			if (results > 0) obj.show();
			else obj.hide();
		} else {
			obj.dataObj.unRead = 0;
			obj.setUnread(0);
			try { setModuleTitle();displayEmails2(); } catch(e) {};
			obj.restoreStatus();
		}
		return false;
	};

};
